//
//  BallLayer.m
//  lust
//
//  Created by fan on 13-3-26.
//
//

#import "BallLayer.h"
#import "Ball.h"
@implementation BallLayer
#define PTM_RATIO 32
static BallLayer* instance=nil;
static b2World* world=nil;

+(BallLayer*) instance
{
    if (instance==nil) {
        instance=[[BallLayer alloc]init];
    }
    return instance;
}

+(CCScene *)scene
{
    CCScene* scene=[CCScene node];
    BallLayer* bl=[BallLayer node];
    [scene addChild:bl];
    return scene;
}
+(b2World*)world
{
    if (world==nil) {
        CGSize s = [[CCDirector sharedDirector] winSize];
        b2Vec2 gravity;
        gravity.Set(0.f,-2.f);
        world=new b2World(gravity);
        world->SetAllowSleeping(true);
        world->SetContinuousPhysics(true);
//        world->Step(<#float32 timeStep#>, <#int32 velocityIterations#>, <#int32 positionIterations#>)
        b2BodyDef groundBodyDef;
        groundBodyDef.position.Set(0, 0); // bottom-left corner
        
        // Call the body factory which allocates memory for the ground body
        // from a pool and creates the ground box shape (also from a pool).
        // The body is also added to the world.
        b2Body* groundBody = world->CreateBody(&groundBodyDef);
        
        // Define the ground box shape.
        b2EdgeShape groundBox;
        
        // bottom
        
        groundBox.Set(b2Vec2(0,0), b2Vec2(s.width/PTM_RATIO,0));
        groundBody->CreateFixture(&groundBox,0);
        
        // top
        groundBox.Set(b2Vec2(0,s.height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,s.height/PTM_RATIO));
        groundBody->CreateFixture(&groundBox,0);
        
        // left
        groundBox.Set(b2Vec2(0,s.height/PTM_RATIO), b2Vec2(0,0));
        groundBody->CreateFixture(&groundBox,0);
        
        // right
        groundBox.Set(b2Vec2(s.width/PTM_RATIO,s.height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,0));
        groundBody->CreateFixture(&groundBox,0);
    }
    return world;
}
-(id)init
{
    self=[super init];
    if (self) {
        instance=self;
        self.isTouchEnabled=true;
        self.isAccelerometerEnabled=true;
        world=[BallLayer world];
       
        Ball* b=[[Ball alloc]init];
//         [self schedule:@selector(tick:)];
        [self scheduleUpdate];
    }
    return self;
}

-(void)update:(ccTime)dt
{
    for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
    {
        Ball* ball=(Ball*)b->GetUserData();
        [ball updatePosition: b->GetPosition()];
        
    }
    
    int32 velocityIterations = 8;
	int32 positionIterations = 1;
	
	// Instruct the world to perform a single step of simulation. It is
	// generally best to keep the time step and iterations fixed.
	world->Step(dt, velocityIterations, positionIterations);

}

-(void)tick:(ccTime)dt
{
    
}
@end
